package com.itcast.ui;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


import com.itcast.util.TextViewLink;
import com.itcast.logic.MainService;
import com.itcast.logic.Task;
import com.itcast.util.NetUtil;
import com.itcast.*;

import weibo4android.Comment;
import weibo4android.Emotion;
import weibo4android.Paging;
import weibo4android.Trend;
import weibo4android.Trends;
import weibo4android.User;
import weibo4android.WeiboException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class CommentActivity extends Activity implements TextWatcher,
		OnClickListener {
	private View title;
	private Button back, send;
	private TextView titleTv, tvCmtLabel, trend, mention, emotion;
	private EditText editText;
	private CheckBox rb_forward;
	private GridView myGridView;
	private long id = 0;
	private ListView myListView;
	private ArrayList<HashMap<String, String>> myList;
	private SimpleAdapter mSchedule;
	public static MyAdapter myAdapter;

	// 定义Handler对象
	public static Handler handler = new Handler() {
		@Override
		// 当有消息发送出来的时候就执行Handler的这个方法
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			myAdapter.notifyDataSetChanged();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		try {
			id = getIntent().getExtras().getLong("id");
			if (id == 0) {
				finish();
			}
		} catch (Exception e) {
			Log.e("CommentActivity", "onCreate");
			finish();
		}

		setContentView(R.layout.comment);

		title = findViewById(R.id.title);
		titleTv = (TextView) findViewById(R.id.textView);
		titleTv.setText("评论微博");
		back = (Button) findViewById(R.id.title_bt_left);
		back.setText(R.string.imageviewer_back);
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (myGridView.getVisibility() == View.VISIBLE) {
					myGridView.setVisibility(View.GONE);
				} else if (myListView.getVisibility() == View.VISIBLE) {
					myListView.setVisibility(View.GONE);
				} else if (editText.getText().toString().length() != 0) {
					dialog();
				} else
					finish();
			
			}

		});

		send = (Button) findViewById(R.id.title_bt_right);
		send.setText(R.string.title_button_send);
		send.setOnClickListener(this);
		editText = (EditText) findViewById(R.id.etCmtReason);
		editText.setHeight(300);
		editText.addTextChangedListener(this);

		
		
		tvCmtLabel = (TextView) findViewById(R.id.tvCmtLabel);
		tvCmtLabel.setText("140");
		rb_forward = (CheckBox) findViewById(R.id.rb_forward);

		myGridView = (GridView) findViewById(R.id.myGridView);
		myListView = (ListView) findViewById(R.id.myListView);
		trend = (TextView) findViewById(R.id.trend);
		mention = (TextView) findViewById(R.id.mention);
		emotion = (TextView) findViewById(R.id.emotion);
		// myListView.setOnScrollListener(new ScrollListener());

		trend.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				editText.setHeight(50);
				toTrend();
			}
		});

		mention.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				editText.setHeight(50);
				toMention();
			}
		});

		emotion.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				editText.setHeight(250);
				toEmotion();
			}
		});

	}

	protected void toEmotion() {
		// TODO Auto-generated method stub
		//下边2句注释掉代码表示进行下载获取
//		Task ts = new Task(Task.TASK_GET_EXPRESSION_IMAGE_ICON, null);
//		MainService.addNewTask(ts);

		
		myGridView.setVisibility(View.VISIBLE);
		myGridView.setNumColumns(6);
		myAdapter = new MyAdapter(this);
		myGridView.setAdapter(myAdapter);

		OnItemClickListener itemListener = new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				final String message = "OnTouchGrid:Icon No." + id
						+ " is Touched.";
				Toast.makeText(getApplicationContext(), message, 1000).show();

				editText.setHeight(300);

				// 得到drawable对象，即所有插入的图片
				Drawable d = getResources().getDrawable(myAdapter.imgs[position]);
				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
				// 用这个drawable对象代替字符串
				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
				String picName = getResources().getResourceName(myAdapter.imgs[position]).split("/")[1];
				String phrase ="["+ TextViewLink.getPicDescription(picName, getApplicationContext()) +"]";
				SpannableString ss = new SpannableString(phrase);
				// 包括0但是不包括phrase.length()
				ss.setSpan(span, 0, ss.length(),
						Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
				editText.append(ss);
				
				myGridView.setVisibility(View.GONE);
				Log.d("QQQ", "OnItemClickListener");
			}
		};
		myGridView.setOnItemClickListener(itemListener);
	}

	protected void toMention() {
		// TODO Auto-generated method stub
		Toast.makeText(getApplicationContext(), "mention", Toast.LENGTH_LONG)
				.show();
		// editText.setHeight(20);

		// 绑定XML中的ListView，作为Item的容器
		
		myListView.setVisibility(View.VISIBLE);
		// 生成动态数组
		myList = new ArrayList<HashMap<String, String>>();
		List<User> userList = null;
		try {
			userList = MainService.mainService.weibo.getFriendsStatuses();
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		HashMap<String, String> map = new HashMap<String, String>();
		map.put("friendName", "@");
		myList.add(map);
		for (int i = 0; i < userList.size(); i++) {
			User friend = userList.get(i);
			String name = friend.getName();
			map = new HashMap<String, String>();
			map.put("friendName", name);
			myList.add(map);
			Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT)
					.show();
		}

		// 生成适配器，数组===》ListItem
		mSchedule = new SimpleAdapter(this, // 没什么解释
				myList,// 数据来源
				R.layout.friend_item,// ListItem的XML实现
				// 动态数组与ListItem对应的子项
				new String[] { "friendName" },

				// ListItem的XML文件里面的TextView ID
				new int[] { R.id.friend });

		myListView.setAdapter(mSchedule);
		myListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub

				String friendName = (String) myList.get(arg2).get("friendName");

				Toast.makeText(getApplicationContext(),
						"你点击了" + arg2 + "项的" + friendName, Toast.LENGTH_SHORT)
						.show();
				editText.setHeight(300);
				if (friendName == "@")
					editText.append("@");
				else
					editText.append("@" + friendName + " ");

				myListView.setVisibility(View.GONE);
			}
		});

	}

	protected void toTrend() {
		// TODO Auto-generated method stub

		// 绑定XML中的ListView，作为Item的容器
		myListView.setVisibility(View.VISIBLE);

		List<Trends> trendList = null;
		try {
			trendList = MainService.mainService.weibo.getTrendsWeekly(0);
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		HashMap<String, String> map = new HashMap<String, String>();
		// 生成动态数组
		myList = new ArrayList<HashMap<String, String>>();
		map.put("friendName", "##");
		myList.add(map);
		for (int i = 0; i < trendList.size(); i++) { // 事实上，这里的trendList.size()�?
			Trends trend = trendList.get(i);
			Trend[] news = trend.getTrends();
			for (int j = 0; j < news.length; j++) {
				String trendName = news[j].getName();
				map = new HashMap<String, String>();
				map.put("friendName", trendName);
				myList.add(map);
				Toast.makeText(getApplicationContext(), trendName,
						Toast.LENGTH_LONG).show();
			}
		}
		// 生成适配器，数组===》ListItem
		mSchedule = new SimpleAdapter(this, // 没什么解释
				myList,// 数据来源
				R.layout.friend_item,// ListItem的XML实现
				// 动态数组与ListItem对应的子项
				new String[] { "friendName" },

				// ListItem的XML文件里面的TextView ID
				new int[] { R.id.friend });

		myListView.setAdapter(mSchedule);
		myListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub

				String friendName = (String) myList.get(arg2).get("friendName");

				Toast.makeText(getApplicationContext(),
						"你点击了" + arg2 + "项的" + friendName, Toast.LENGTH_SHORT)
						.show();

				editText.setHeight(300);
				if (friendName == "##") {
					editText.append("##");
					editText.requestFocus();
					editText.setSelection(editText.length() - 1);
				} else
					editText.append("#" + friendName + "# ");

				myListView.setVisibility(View.GONE);
			}
		});
	}

	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		int i = 140 - arg0.length();
		tvCmtLabel.setText("" + i);
	}

	public void onClick(View v) {
		if (editText.getText().length() <= 140) {
			HashMap hm = new HashMap();
			String comment = editText.getText().toString();
			hm.put("msg", comment);
			hm.put("id", String.valueOf(id));
			if (rb_forward.isChecked()) {
				hm.put("news", new Boolean(true));
			} else {
				hm.put("news", new Boolean(false));
			}
			Task ts = new Task(Task.TASK_NEW_WEIBO_COMMENT, hm);
			MainService.addNewTask(ts);
			Toast.makeText(getApplicationContext(),
					editText.getText().toString(), 3000).show();
			finish();
		} else
			Toast.makeText(getApplicationContext(), "字数超出限制", 3000).show();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	public void afterTextChanged(Editable arg0) {
	}

	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (myGridView.getVisibility() == View.VISIBLE) {
				myGridView.setVisibility(View.GONE);
				Toast.makeText(getApplicationContext(),
						myGridView.getVisibility() + "", 3000).show();
				return false;
			} else if (myListView.getVisibility() == View.VISIBLE) {
				myListView.setVisibility(View.GONE);
				Toast.makeText(getApplicationContext(),
						myGridView.getVisibility() + "", 3000).show();
				return false;
			} else if (editText.getText().toString().length() != 0) {
				dialog();
				return false;
			} else
				return super.onKeyDown(keyCode, event);
		}
		return super.onKeyDown(keyCode, event);
	}

	//在退出前进行询问
	protected void dialog() {
		AlertDialog.Builder builder = new Builder(CommentActivity.this);
		builder.setMessage("确定要退出编辑吗?");
		builder.setTitle("提示");
		builder.setPositiveButton("确认",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						// TODO Auto-generated method stub
						arg0.dismiss();
						CommentActivity.this.finish();
					}
				});
		builder.setNegativeButton("取消",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}

	static class MyAdapter extends BaseAdapter {
		public Integer[] imgs = {
    			R.drawable.aini,
    			R.drawable.aoteman,
    			R.drawable.baibai,
    			R.drawable.baobao,
    			R.drawable.beishang,
    			R.drawable.bishi,
    			R.drawable.bizui,
    			R.drawable.buyao,
    			R.drawable.chanzui,
    			R.drawable.chijing,
    			
    			R.drawable.dahaqi,
    			R.drawable.dangao,
    			R.drawable.ding,
    			R.drawable.ganmao,
    			R.drawable.geili,
    			R.drawable.good,
    			R.drawable.guzhang,
    			R.drawable.haha,
    			R.drawable.haixiu,
    			R.drawable.han,
    			
    			R.drawable.hehe,
    			R.drawable.heixian,
    			R.drawable.heng,
    			R.drawable.huatong,
    			R.drawable.huaxin,
    			R.drawable.hufen,
    			R.drawable.jiong,
    			R.drawable.jiyan,
    			R.drawable.keai,
    			R.drawable.kelian,
    			
    			R.drawable.ku,
    			R.drawable.kun,
    			R.drawable.lai,
    			R.drawable.landelini,
    			R.drawable.lazhu,
    			R.drawable.lei,
    			R.drawable.liwu,
    			R.drawable.nu,
    			R.drawable.numa,
    			R.drawable.ok,
    			
    			R.drawable.qian,
    			R.drawable.qinqin,
    			R.drawable.quantou,
    			R.drawable.ruo,
    			R.drawable.shangxin,
    			R.drawable.shengbing,
    			R.drawable.shenma,
    			R.drawable.shiwang,
    			R.drawable.shuai,
    			R.drawable.shudaizi,
    			
    			R.drawable.shuijiao,
    			R.drawable.sikao,
    			R.drawable.taikaixin,
    			R.drawable.touxiao,
    			R.drawable.tu,
    			R.drawable.tuzi,
    			R.drawable.wabishi,
    			R.drawable.weiqu,
    			R.drawable.woshou,
    			R.drawable.xin,
    			
    			R.drawable.xiongmao,
    			R.drawable.xixi,
    			R.drawable.xu,
    			R.drawable.ye,
    			R.drawable.yinxian,
    			R.drawable.yiwen,
    			R.drawable.youbaobao,
    			R.drawable.youhengheng,
    			R.drawable.yun,
    			R.drawable.zan,
    			
    			R.drawable.zhi,
    			R.drawable.zhong,
    			R.drawable.zhuakuang,
    			R.drawable.zhutou,
    			R.drawable.zuobaobao,
    			R.drawable.zuohengheng
    	};
 
		
		Context context;

		MyAdapter(Context context) {
			this.context = context;
		}

		public int getCount() {
			
			return imgs.length;

			
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return imgs[position];
		}

		

		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView imageView;
			if (convertView == null) {
				imageView = new ImageView(context);
				imageView.setLayoutParams(new GridView.LayoutParams(45, 45));
				imageView.setAdjustViewBounds(false);
				imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
				imageView.setPadding(8, 0, 8, 8);
			} else {
				imageView = (ImageView) convertView;
			}
			 imageView.setImageResource(imgs[position]);
			 //下面注释掉的代码是从网上下载的方式
//			if (MainService.myExpression.get(position) != null) {
//				
//				imageView.setImageDrawable(MainService.myExpression
//						.get(position));
//			}
			return imageView;
		}

		
		

	}
}
